/**
 * 树形下拉选择公共组件
 * 使用：
 *
 * 返回数据结构要求：
 * {
    "obj": [
    {
        "name": "建筑工程",
        "pId": "GCZYLB_1000",
        "id": "GCZYLB_1100"
    },
    {
        "canSelect": "1",
        "name": "民用建筑工程",
        "pId": "GCZYLB_1100",
        "id": "GCZYLB_1101"
    }],
    "status": 200,
    "success": true
}

 说明 name;树节点名称
 id:树节点id
 pId：树节点的父节点
 canSelect: 1代表是选择项 0非选择项（点击不会收起下拉框且不会调用回调）
 * @type {string} ywc
 */
window.treeIds = 0;
;(function () {


  //选择容器
  // var container = '<div id="treeWrapper" class="treeWrapper" style="display:none; position: absolute;"><ul id="treeContent" class="ztree" style="margin-top:0; width:160px;"></ul></div>';
  var container = '<div id="{wid}" class="{wclass}" style="display:none; position: absolute;"><ul id="{tid}" class="ztree" style="margin-top:0; width:160px;"></ul></div>';
  var zNodes = [
    {id: 1, pId: 0, name: "北京", "canSelect": "1"},
    {id: 2, pId: 0, name: "天津", "canSelect": "1"},
    {id: 64, pId: 6, name: "三明", "canSelect": "1"}
  ];
  var defaults = {
    url: '',//获取树结构数据的url
    params: {},//获取树结构数据的参数
    expandAll: true,//是否默认展开所有节点
    exeWidth: 0,//下拉框宽度修正值
    maxHeight: '100px',//下拉框最大高度
    minHeight: "80px",
    multiple: false,//单选or多选
    callback: $.noop,//点击回调，一般用于将选中值显示在页面上
  };

  var treeSelect = function (ele, settings) {
    window.treeIds++;
    var $this = this;
    var index = window.treeIds + 1;
    var wid = "treeWrapper" + index;
    var wClass = "treeWrapper" + index;
    var treeId = "treeContent" + index;
    // var treeCls="ztree"+index;

    var $ele = ele;
    var option = settings;

    var treeObj;
    var setting = {
      view: {
        dblClickExpand: false
      },
      data: {
        /*  key: {
            name: "dataValue",
            title: "dataValue"
          },*/
        simpleData: {
          enable: true,
          /*  idKey: "id",
            pIdKey: "parentId",
            rootPId: 0*/
        }
      },
      check: {
          enable: true,
          autoCheckTrigger: true,
          chkboxType: { "Y": "s", "N": "ps" }
      },
      callback: {
        /*beforeClick: beforeClick,*/
        onClick: $.noop
      }
    };

    //多选时选中已选的项
    this.checkNodes = function () {
      if (option.multiple) {
        var values = $($ele).data("values")
        values = values && values.split(',');
        if (values && values.length > 0) {
          var nodes = [];
          $.each(values, function (i, id) {
            var node = treeObj.getNodeByParam("id", id, null);
            if (node) {
              treeObj.checkNode(node, true, true);
              $this.zTreeOnCheck(null, null, node);
            }
          });
        }
      }
    };

    //点击树节点事件
    this.treeOptionOnClick = function (e, treeId, treeNode) {
      treeObj.checkNode(treeNode, undefined, true, true);
      var treeNodes = [];
      if (treeNode.canSelect === "1") {
        if (!option.multiple) {
          $this.hideTreeSelect();
          treeNodes = [];
          treeNodes.push(treeNode);
        } else {
          var nodes = treeObj.getCheckedNodes(true);
          treeNodes = (nodes);
        }

        option.callback($this.formatterReturn(treeNodes));
      }
    };

    this.zTreeOnCheck = function (event, treeId, treeNode) {
      treeObj.selectNode(treeNode);//选择点
      var nodes = treeObj.getCheckedNodes(true);
      option.callback($this.formatterReturn(nodes));
    }

    this.formatterReturn = function (treeNodes) {
      var tmpArray = [];
      $.each(treeNodes, function (i, item) {
        tmpArray.push({"id": item.id, "name": item.name})
      });
      return tmpArray;
    };

    //初始化容器
    this.bodyAppendTreeContainer = function () {

      var pidx = $($ele).data("index");

      if (pidx) {
        $("#treeWrapper" + pidx).remove();
      }
      $($ele).data("index", index);
      var html = container.replace("{wid}", wid).replace("{wclass}", wClass).replace("{tid}", treeId);
      $("body").append(html);
      $("." + wClass).css("max-height", option.maxHeight).css("minHeight", option.minHeight);


    };

    //初始化ztree
    this.initTreeSelect = function () {
      setting.callback.onClick = this.treeOptionOnClick;
      if (option.multiple) {
        setting.check.enable = true;
        setting.callback.onCheck = this.zTreeOnCheck;
      } else {
        setting.check.enable = false;
      }
      treeObj = $.fn.zTree.init($("#" + treeId), setting, zNodes);
      option.expandAll ? treeObj.expandAll(true) : "";

      $(ele).click(function () {
        if ($("." + wClass).is(":hidden") || !$("." + wClass).is(":visible")) {
          $this.showTreeSelect();
        }
      });
    };

    //显示下拉框
    this.showTreeSelect = function () {
      var cityObj = $(ele);
      var cityOffset = $(ele).offset();
      $("#" + wid).css({
        left: cityOffset.left + "px",
        top: cityOffset.top + cityObj.outerHeight() + "px",
        width: cityObj.width() + option.exeWidth + "px"
      }).slideDown("fast");

      //点击页面其他区域收起下拉框
      $("body").bind("mousedown", function (event) {
        if (!(event.target.id == $($ele).attr("id") || event.target.id == wid || $(event.target).parents("#" + wid).length > 0)) {
          $this.hideTreeSelect();
        }
      });
    };

    //隐藏下拉框
    this.hideTreeSelect = function () {
      $("#" + wid).fadeOut("fast");

    };

    //div发生滚动时收起下拉框
    this.scrollListener = function () {
      $("div").scroll(function () {
        var clses = $(this).attr("class");
        if (clses) {
          var clsArray = clses.split(" ");
          // $.inArray('treeWrapper', clsArray) === -1 ? $this.hideTreeSelect() : "";
          $.inArray(wClass, clsArray) === -1 ? $("#" + wid).hide() : "";
        }
      });
    };

    //远程加载数据
    this.getAjaxData = function () {
      $.ajax({
        url: option.url,
        data: option.params,
        success: function (data) {
          zNodes = data.obj;
          $this.init();
          if (zNodes && zNodes.length == 0) {
            $("#" + treeId).html("无数据")
          }
        }
      });
    };


    this.init = function () {
      this.bodyAppendTreeContainer();
      this.initTreeSelect();
      this.scrollListener();
      this.checkNodes();
    };

    this.getAjaxData();
  };

  $.fn.treeSelect = function (settings) {
    var options = $.extend({}, defaults, settings);
    return this.each(function () {
      new treeSelect(this, options);
    });
  }


})(jQuery);